package com.xy.wsl.api.controller.Image;

import com.xy.wsl.api.response.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@RequestMapping("/image")
@Slf4j
@RestController
public class ImageController {


    @PutMapping("rgb")
    public Object imageToRgb(@RequestParam("file") MultipartFile file) {

        try {
            // 读取jpg图片
            BufferedImage image = ImageIO.read(file.getInputStream());

            // 获取图片的宽度和高度
            int width = image.getWidth();
            int height = image.getHeight();
            System.out.println("width:" + width + " height:" + height);
            // 创建存储像素数据的数组
            byte[] rgb565 = new byte[width * height];
//            List<String> rgb565 = new ArrayList<>();
            for (int y = 0; y < height; y++) {
                for (int x = 0; x < width; x++) {
                    int rgb = image.getRGB(x, y);
                    int r = (rgb >> 16) & 0x1F; // 取红色位
                    int g = (rgb >> 8) & 0x3F;  // 取绿色位
                    int b = rgb & 0x1F;         // 取蓝色位
                    int rgb565Value = (r << 11) | (g << 5) | b;
                    rgb565[y * width + x] = (byte) rgb565Value;
//                    rgb565.add(String.format("0x%04X", rgb565Value));
                }
            }

            return rgb565;

        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
